import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/services/HttpApi.dart';
import 'package:flutter_demo/states/message_state.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:uuid/uuid.dart';

import '../models/message.dart';
import '../services/injection.dart';
import '../states/chat_ui_state.dart';
const uuid = Uuid();
class UserInputWidget extends HookConsumerWidget{
    const UserInputWidget({super.key});
    // static
  @override
  Widget build(BuildContext context, WidgetRef ref) {
     final chatUIState = ref.watch(chatUiProvider);
     final controller = TextEditingController();
     return TextField(
       enabled: !chatUIState.requestLoading,
       controller: controller,
       decoration: InputDecoration(
         hintText: 'Type a message',
         suffixIcon: IconButton(
             onPressed: () async {
             var responseData = await HttpApi.request('/register', method: 'post');
              print(responseData);
             if (controller.text.isNotEmpty) {
                 _sendMessage(ref, controller);
               }
         },icon: const Icon(
           Icons.send
         )
         )
       ),
     );
     return Text('');
  }
   _sendMessage(WidgetRef ref, TextEditingController controller) async{
      final content  = controller.text;
      final message = Message(
          content: content,
          isUser: true,
          timestamp: DateTime.now(),
          id: uuid.v4()
      );
      ref.read(messageProvider.notifier).addMessage(message);
      controller.clear();
   }

    _requestChatGPT(WidgetRef ref, String content) async {
      ref.read(chatUiProvider.notifier).setRequestLoading(true);
      try {
        final id = uuid.v4();
        // await chatgpt.streamChat(
        //   content,
        //   onSuccess: (text) {
        //     final message = Message(
        //       id: id,
        //       content: text,
        //       isUser: false,
        //       timestamp: DateTime.now(),
        //     );
        //     ref.read(messageProvider.notifier).addMessage(message);
        //   },
        // );
      } catch (err) {
        // logger.e("requestChatGPT error: $err", err);
      } finally {
        ref.read(chatUiProvider.notifier).setRequestLoading(false);
      }
    }
}